<template>
  <div class="home">
    <h2>代办事项</h2>
    <add @add-item="addItem"></add>
    <tags @update-item-class="updateItemClass"></tags>
    <ul>
      <p v-if="filteredItems.length === 0">暂无任务</p>
      <div v-else>
        <main-item :items=filteredItems  @toggle-item="toggleItem" @edit-item="editItem" @save-edit="saveEdit" @delete-item="deleteItem"></main-item>
      </div>
    </ul>
    <hr>
    <count :items=filteredItems></count>
    
  </div>
</template>

<script>
  import add from './components/add.vue'
  import tags from './components/tags.vue'
  import count from './components/count.vue'
  import mainItem from './components/main.vue'
    
  export default {
    components: {
      add, tags, count, mainItem,
    },
    data() {
      return {
        items: localStorage.getItem('items')? JSON.parse(localStorage.getItem('items')) : [],
        itemClass: '',
        editingId: '',
        editingText: '',
        editingClass: ''
      }
    },
    computed: {
      filteredItems() {
        if (!this.itemClass) return this.items;
        return this.items.filter(item => item.itemClass === this.itemClass);
      },
    },
    methods: {
      addItem(newItem) {
        const item = {
          id : new Date().getTime(),
          text: newItem,
          itemClass: "work",
          over: false
        };
        this.items.push(item);
        this.newItem = '';
      },
      updateItemClass(newClass) {
        this.itemClass = newClass;
      },
      setItem() {
        localStorage.setItem('items', JSON.stringify(this.items));
      },
      editItem(item) {
        const {id, text, itemClass} = item;
        this.editingId = id;
        this.editingText = text;
        this.editingClass = itemClass.value;
      },
      saveEdit() {
        const item = this.items.find(i => i.id === this.editingId);
        if (!item) return;
        item.text = this.editingText;
        item.itemClass = this.editingClass;
        this.editingId = '';
        this.editingText = '';
        this.editingClass = '';
        this.setItem();
      },
      deleteItem(item) {
        this.items = this.items.filter(i => i.id !== item.id);
        this.setItem();
      },
      toggleItem(id) {
        const item = this.items.find(i => i.id === id);
        if (!item) return;
        item.over = !item.over;
        this.setItem();
      },
    }
  }
</script>
<style scoped>
  .home {
    width: 700px;
    margin: 0 auto;
    padding: 20px 50px;
    text-align: center;
    border: 1px solid #ccc;
    border-radius: 5px;
    box-shadow: 0 0 10px #ccc;
  }
  h2 {
    margin: 20px;
    font-size: 38px;
  }
</style>
